<template>
  <div class="comdiv">

    <happy-scroll color="#ccc" size="5" class="layout-scrollbar__wrap" resize hide-horizontal>
      <div class="con" ref="bgImage">
        <!-- search1 -->
        <search-temp
          :listQuery="listQuery.searchText"
          @doSearch="handleFilter"
          @handleCreate="handleCreate"
          :placeholder="placeholder"
        ></search-temp>
        <!--table-->
        <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
          <el-table-column align="center" label="序号" width="60">
            <template slot-scope="scope"><span>{{scope.row.px}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="id" width="60">
            <template slot-scope="scope"><span>{{scope.row._id}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="区域" prop="areaId" width="100">
            <template slot-scope="scope"><span>{{scope.row.area.areaName}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="公司" prop="companyName" width="200">
            <template slot-scope="scope"><span>{{scope.row.companyName}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="公司全称" prop="companyFullName" width="300">
            <template slot-scope="scope"><span>{{scope.row.companyFullName}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="公司类型" prop="companyType" width="150">
            <template slot-scope="scope"><span>{{scope.row.companyType|$_filterType}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="地址" prop="companyAddress" width="300">
            <template slot-scope="scope"><span>{{scope.row.companyAddress}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remark" width="300">
            <template slot-scope="scope"><span>{{scope.row.remark}}</span></template>
          </el-table-column>
          <el-table-column align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <!--<el-button type="success" plain @click="handleUpdate(scope.row)" size="small">-->
              <el-button type="primary" plain @click="handleUpdate(scope.row)" size="small">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--add-->
        <el-dialog :title="dialogStatus=='create'?'添加公司':'修改公司'" :visible.sync="dialogFormVisible" top="1vh">
          <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px"
                   style='width: 450px; margin-left:50px;'>
            <el-form-item label="区域" prop="areaId">
              <el-select v-model="temp.areaId" placeholder="请选择">
                <el-option v-for="vd in selectAreas" :key="vd._id" :value="vd._id" :label="vd.areaName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="公司名" prop="companyName">
              <el-input v-model="temp.companyName"></el-input>
            </el-form-item>
            <el-form-item label="公司全称" prop="companyFullName">
              <el-input v-model="temp.companyFullName"></el-input>
            </el-form-item>
            <el-form-item label="公司类型" prop="companyType">
              <el-radio-group v-model="temp.companyType" size="mini">
                <el-radio v-for="(value, key) in _CompanyType"  :key="key" :label="key">{{value}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="地址" prop="companyAddress">
              <el-input v-model="temp.companyAddress"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input :autosize="{ minRows: 1, maxRows: 4}" v-model="temp.remark" type="textarea" placeholder="备注"/>
            </el-form-item>
            <el-form-item label="经度/纬度" prop="">
              <el-input v-model="temp.lng"></el-input>
              <el-input v-model="temp.lat"></el-input>
            </el-form-item>
          </el-form>

          <div class="amap-page-container" style="width: 600px; height: 600px; margin: 0 auto;">
            <el-amap ref="gdmap" vid="amapDemo" :center="marker.center" :zoom="marker.zoom"
                     :plugin="marker.plugin" class="amap-demo">
              <el-amap-marker :position="marker.position"
                              :events="marker.events"
                              :visible="marker.visible"
                              :draggable="marker.draggable"
                              vid="demo1"
              ></el-amap-marker>
              <div class="toolbar">
                <span v-if="loaded">
                  location: lng = {{ temp.lng }} lat = {{ temp.lat }}
                </span>
                <span v-else>正在定位</span>
              </div>
            </el-amap>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button v-if="dialogStatus=='create'" type="primary" @click="createData" id="cfmbtm1">添加</el-button>
            <el-button v-else type="primary" @click="updateData" id="cfmbtm2">修改</el-button>
          </div>
        </el-dialog>
        <!--edit-->
        <!--分页组件-->
        <!--<pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size"-->
                    <!--@pagination="getList"/>-->

      </div>

    </happy-scroll>


  </div>
</template>

<script>

  /* eslint-disable */
  import {
    fetchGet,
    areasAll,
    createOne,
    updateOne,
    deleteOnePut
  } from '@/api/common'
  import {disableBtn, ERRS, SUCS} from '@/utils'
  import Pagination from '@/components/Pagination'
  import searchTemp from '@/components/viewComponents/search2'
  import mixinAr from './comp/mixinAr'
  // import $ from 'jquery'
  export default {
    name: 'companyList',
    // search2 引入 and search3 声明
    components: {Pagination, searchTemp},
    mixins: [mixinAr],
    data() {
      let self = this
      return {
        url: 'auth/companies',
        list: null,
        // total: 110,
        px: null, //最大序号
        listLoading: true,
        placeholder: '公司', //search4
        listQuery: {
          page: 1,
          size: 20, //每页几条
          number: 0, //当前页为第1页,从0计算
          searchText: undefined,
        },
        //弹出层
        dialogFormVisible: false,
        dialogStatus: 'create',
        //selectOption
        selectAreas:[],

        //高德amap  https://elemefe.github.io/vue-amap/#/zh-cn/base/amap
        position:[118.384203, 31.339229], //自动定位的当前地址
        loaded: false,
        marker: {
          zoom: 12,
          center: [118.384203, 31.339229],  //中心点
          position: [118.384203, 31.339229],  //定位点
          events: {
            click: () => {
              console.log('click marker');
            },
            dragend: (e) => {
              console.log('经纬度',e.lnglat.lng,e.lnglat.lat)
              self.marker.position = [e.lnglat.lng, e.lnglat.lat];
              self.temp.lng = e.lnglat.lng
              self.temp.lat = e.lnglat.lat
            }
          },
          visible: true,
          draggable: true, //true 点可拖动
          template: '<span>坐标</span>',
          plugin: [
            {
              pName: 'Geolocation',
              events: {
                init(o) {
                  // o 是高德地图定位插件实例 第一次添加时调用
                  if(self.dialogStatus=='create'){
                    o.getCurrentPosition((status, result) => {
                      console.log('定位',status, result)
                      if (result && result.position) {
                        let lng=result.position.lng;
                        let lat=result.position.lat;
                        self.position = [lng, lat];
                        self.temp.lng = lng;
                        self.temp.lat = lat;

                        self.marker.position = [lng, lat];
                        self.marker.center = [lng, lat]; //中心
                        self.loaded = true;
                        self.$nextTick()
                      }
                    });
                  }

                }
              }
            },
            {
              pName: 'ToolBar',
              events: {
                init(instance) {
                  console.log(instance);
                }
              }
            },
          ]
        },
        temp: {},   //保存添加,编辑后提交的信息
        rules: {
          areaId: [
            {required: true, message: '请选择区域', trigger: 'blur'}
          ],
          companyName: [
            {required: true, message: '请输入公司名', trigger: 'blur'}
          ],
        },
      }
    },
    mounted() {
      this.getAll()
      this.getList();
    },
    methods: {

      getAll(){
        //地区
        areasAll().then(res => {
          if (res.code == 0) {
            this.selectAreas = res.data;
          } else {
            ERRS('地区调用Err: '+res.message)
          }
        })
      },
      ////search5
      handleFilter(val) {
        this.listQuery.searchText = val;
        this.getList()
      },

      getList() {
        this.listLoading = true;
        fetchGet(this.url + `/all`).then(res => {
          console.log(res);
          if (res.code == 0) {
            let dat = res.data
            // this.listQuery.size = dat.size ? dat.size : 10; //每页几条
            // this.listQuery.page = dat.page ? dat.page : 1; //当前页为第1页
            this.list = dat;
            let insIndex = this.listQuery.size * (this.listQuery.page - 1);
            this.list = this.list.map((v, index) => {
              this.$set(v, 'px', insIndex + index + 1);
              // this.$set(v, 'roles',insIndex+index+1);
              this.px = insIndex + index + 1; //最大序号
              return v
            });

            this.$nextTick()
          } else {
            ERRS(res.message)
          }
          this.listLoading = false
        })
      },

      handleCreate() {
        this.temp = {
          areaName: '',
          areaId: '',
          companyAddress: "",
          companyFullName: "",
          companyName: "",
          companyType: "CHILD", //GROUP, CHILD
          lng: this.position[0],   //经度
          lat: this.position[1],   //纬度
          remark: ""
        };

        this.marker.position = [this.position[0], this.position[1]];
        this.marker.center = [this.position[0], this.position[1]];
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //添加提交
      createData() {
        console.log( this.temp);
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm1');
            createOne(this.url, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('添加成功!')
                this.getList();
              } else {
                ERRS(res.message)
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
      //详情修改
      handleUpdate(row) {
        console.log(row);
        this.temp = {
          id: row._id,
          areaId: row.area._id,
          companyAddress: row.companyAddress,
          companyFullName: row.companyFullName,
          companyName: row.companyName,
          companyType:row.companyType, //GROUP, CHILD
          lng: row.lng,
          lat: row.lat,
          remark: row.remark
        }

        this.marker.position = [row.lng, row.lat];
        this.marker.center = [row.lng, row.lat]; //中心

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        })
      },
      //修改提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm2');
            // delete tempData.createdTime;
            updateOne(this.url, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('修改成功!')
                this.getList();
              } else {
                ERRS(res.message)
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
      //删除
      handleDelete(row) {
        console.log(row);
        this.$msgbox({
          // title: '删除',
          message: '确定要删除吗?',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOnePut(`auth/companies/freeze`,row._id).then(res => {
            if (res.code === 0) {
              this.getList();
              SUCS('删除成功!')
            } else {
              ERRS(res.message)
            }
            this.dialogFormVisible = false
          })
        });
      },

    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  @import './comp/index.scss';
</style>
